package me.idashu.attg.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.idashu.attg.domain.GoodsEntity;
import me.idashu.attg.domain.LabelEntity;
import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.domain.ShopEntity;
import me.idashu.attg.service.GoodesService;
import me.idashu.attg.service.LabelSerivce;
import me.idashu.attg.service.ShopService;
import me.idashu.attg.util.Escape;
import me.idashu.attg.util.SystemConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/goods")
public class GoodsController {
	@Autowired
	private ShopService shopService;

	@Autowired
	private LabelSerivce labelService;

	@Autowired
	private GoodesService goodsService;

	@Autowired
	private SystemConfig systemConfig;

	@RequestMapping("/addGoods")
	public String setCirl(Model model) {
		PageEntity pageEntity = new PageEntity();
		ShopEntity shopEntity = new ShopEntity();
		pageEntity.setPageSize(100000000);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shopEntity", shopEntity);
		map.put("pageEntity", pageEntity);
		List<ShopEntity> shops = shopService.findShopsByPage(map);
		List<LabelEntity> goodslabels = labelService.getAllLabelEntity("goods");
		List<LabelEntity> stufflabels = labelService.getAllLabelEntity("stuff");
		model.addAttribute("shops", shops);
		model.addAttribute("goodslabels", goodslabels);
		model.addAttribute("stufflabels", stufflabels);
		model.addAttribute("addGoods", "添加商品");
		return "add_goods";
	}

	@RequestMapping("/addGoodsInfo")
	public String addCirlInfo(
			@ModelAttribute GoodsEntity goodsEntity,
			@RequestParam(value = "file", required = false) MultipartFile[] files,
			Model model, HttpServletRequest request) {
		try {
			String url=null;
			String dir = systemConfig.getDir("dir");
			String prodir = systemConfig.getDir("prodir");
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					MultipartFile file = files[i];
					if (file.getOriginalFilename() != null
							&& !"".equals(file.getOriginalFilename())) {
						System.out
								.println("file:" + file.getOriginalFilename());
						try {
							InputStream is = file.getInputStream();
							byte[] inOutb = new byte[is.available()];
							String uuid = UUID.randomUUID().toString().replace(
									"-", "");
							FileOutputStream fos = new FileOutputStream(
									new File(dir + uuid + ".jpg"));
							if(url ==null){
								url = prodir + uuid + ".jpg";
							}else{
								url = url+","+prodir + uuid + ".jpg";
							}
							is.read(inOutb);
							fos.write(inOutb);
							is.close();
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
			goodsEntity.setImage(url);
			goodsEntity.setTime(new Date());
			goodsEntity.setFlag("Y");
			goodsService.insertGoods(goodsEntity);
			model.addAttribute("success", "添加商品成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success";
	}

	@RequestMapping("/getGoods")
	public String getShops(Model model) {
		model.addAttribute("getGoods", "添加商家");
		GoodsEntity goodsEntity = new GoodsEntity();
		PageEntity pageEntity = new PageEntity();
		selectGoods(model, goodsEntity, pageEntity);
		return "goods_list";
	}

	@RequestMapping("/goodsAjaxList")
	public String shopAjaxList(Model model,
			@ModelAttribute GoodsEntity goodsEntity,
			@ModelAttribute PageEntity pageEntity) {
		if (goodsEntity.getName() != null && !"".equals(goodsEntity.getName())) {
			String title = Escape.unescape(goodsEntity.getName());
			goodsEntity.setName(title);
		}
		if (goodsEntity.getShopname() != null
				&& !"".equals(goodsEntity.getShopname())) {
			String title = Escape.unescape(goodsEntity.getShopname());
			goodsEntity.setShopname(title);
		}
		selectGoods(model, goodsEntity, pageEntity);
		return "goodsAjaxList";
	}

	@RequestMapping("/selectOneGoods")
	public String selectOneShop(Model model, @RequestParam("id") long id) {
		GoodsEntity goods = goodsService.findGoodById(id);
		model.addAttribute("goods", goods);
		return "goods_info";
	}

	private void selectGoods(Model model, GoodsEntity goodsEntity,
			PageEntity pageEntity) {
		int total = goodsService.findCountGoodsByPage(goodsEntity);
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageEntity", pageEntity);
		map.put("goodsEntity", goodsEntity);
		List<GoodsEntity> goods = goodsService.findGoodsByPage(map);
		if (goods.size() > 0) {
			model.addAttribute("goodses", goods);
		} else {
			model.addAttribute("goodses", null);
		}
		model.addAttribute("pageEntity", pageEntity);
	}

	@RequestMapping("/deleteGoods")
	public String deleteShop(Model model,
			@ModelAttribute GoodsEntity goodsEntity,
			@ModelAttribute PageEntity pageEntity) {
		goodsService.deleteGoodsById(goodsEntity.getId());
		if (goodsEntity.getName() != null && !"".equals(goodsEntity.getName())) {
			String title = Escape.unescape(goodsEntity.getName());
			goodsEntity.setName(title);
		}
		if (goodsEntity.getShopname() != null
				&& !"".equals(goodsEntity.getShopname())) {
			String title = Escape.unescape(goodsEntity.getShopname());
			goodsEntity.setShopname(title);
		}
		selectGoods(model, goodsEntity, pageEntity);
		return "goodsAjaxList";
	}

	@RequestMapping(value = "/getLabelList")
	public void preCheckUserName(@RequestParam("uplabelId") int uplabelId,
			HttpServletResponse response) {
		response.setContentType("text/html;charset=GBK");
		try {
			String checkResult = null;
			PageEntity pageEntity = new PageEntity();
			pageEntity.setPageSize(100000000);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("uplabelId", uplabelId);
			map.put("pageEntity", pageEntity);
			List<LabelEntity> listLabel = labelService.getLabelList(map);
			checkResult = "<label class=\"control-label\" for=\"label_id\">商铺小分类</label><div class=\"controls\"><select id=\"label_id\" name=\"label_id\">";
			String context = null;
			for (int i = 0; i < listLabel.size(); i++) {
				LabelEntity labelEntity = listLabel.get(i);
				if (context == null) {
					context = "<option value=" + labelEntity.getLabel_id()
							+ ">" + labelEntity.getLabel_name() + "</option>";
				} else {
					context = context + "<option value="
							+ labelEntity.getLabel_id() + ">"
							+ labelEntity.getLabel_name() + "</option>";
				}
			}
			checkResult = checkResult + context + "</select></div>";
			response.getWriter().print(checkResult);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
